extends Node
class_name Player

# 基本信息
@export var player_name: String = "无名修士"
@export var level: int = 1
@export var experience: int = 0
@export var experience_to_next_level: int = 100

# 修炼境界
enum CultivationRealm {
	QI_REFINING_1,    # 练气期初期
	QI_REFINING_2,    # 练气期中期
	QI_REFINING_3,    # 练气期后期
	FOUNDATION_1,     # 筑基期初期
	FOUNDATION_2,     # 筑基期中期
	FOUNDATION_3,     # 筑基期后期
	CORE_FORMATION_1, # 金丹期初期
	CORE_FORMATION_2, # 金丹期中期
	CORE_FORMATION_3, # 金丹期后期
	NASCENT_SOUL_1,   # 元婴期初期
	NASCENT_SOUL_2,   # 元婴期中期
	NASCENT_SOUL_3,   # 元婴期后期
	DIVINITY_1,       # 化神期初期
	DIVINITY_2,       # 化神期中期
	DIVINITY_3,       # 化神期后期
	ASCENSION         # 飞升期
}

@export var cultivation_realm: int = CultivationRealm.QI_REFINING_1

# 灵根属性
enum SpiritRoot {
	FIRE,      # 火灵根
	WATER,     # 水灵根
	WOOD,      # 木灵根
	METAL,     # 金灵根
	EARTH,     # 土灵根
	WIND,      # 风灵根
	THUNDER,   # 雷灵根
	ICE,       # 冰灵根
	LIGHT,     # 光灵根
	DARK,      # 暗灵根
	CHAOS      # 混沌灵根
}

# 灵根品质
enum SpiritRootQuality {
	WEAK,       # 劣等
	NORMAL,     # 普通
	GOOD,       # 良好
	EXCELLENT,  # 优秀
	SUPERIOR,   # 上品
	SUPREME     # 极品
}

# 灵根配置
@export var spirit_roots: Array = []  # 存储灵根类型
@export var spirit_root_quality: int = SpiritRootQuality.NORMAL

# 基础属性
@export var max_health: int = 100
@export var current_health: int = 100
@export var max_spirit: int = 50  # 真气值
@export var current_spirit: int = 50
@export var attack: int = 10
@export var defense: int = 5
@export var speed: int = 10

# 技能列表
var skills: Array = []  # 已学习的技能
var active_skills: Array = []  # 已装备的技能（战斗中可用）
var max_active_skills: int = 4  # 最多可装备的技能数量

# 装备
var equipment: Dictionary = {}

# 背包
var inventory: Array = []  # 物品列表
var max_inventory_size: int = 20  # 最大背包容量
var spirit_stones: int = 0  # 灵石（货币）

# 修炼功法
var cultivation_technique = null  # 当前修炼的功法

# 信号
signal level_up(new_level, realm_changed)
signal health_changed(current, maximum)
signal spirit_changed(current, maximum)
signal experience_gained(amount, total)
signal inventory_changed()
signal equipment_changed(slot, item)

# 初始化玩家
func _init(p_name: String = "无名修士") -> void:
	player_name = p_name
	name = p_name
	# 初始化属性
	_update_stats()

# 根据等级和境界更新属性
func _update_stats() -> void:
	# 基础属性随等级提升
	max_health = int(100 * (1 + 0.1 * level))
	max_spirit = int(50 * (1 + 0.15 * level))
	attack = int(10 * (1 + 0.1 * level))
	defense = int(5 * (1 + 0.1 * level))
	speed = int(10 * (1 + 0.05 * level))
	
	# 境界加成
	var realm_multiplier = 1.0
	if cultivation_realm >= CultivationRealm.FOUNDATION_1:
		realm_multiplier = 1.5
	elif cultivation_realm >= CultivationRealm.CORE_FORMATION_1:
		realm_multiplier = 2.0
	elif cultivation_realm >= CultivationRealm.NASCENT_SOUL_1:
		realm_multiplier = 3.0
	elif cultivation_realm >= CultivationRealm.DIVINITY_1:
		realm_multiplier = 5.0
	elif cultivation_realm >= CultivationRealm.ASCENSION:
		realm_multiplier = 10.0
	
	# 应用境界加成
	max_health = int(max_health * realm_multiplier)
	max_spirit = int(max_spirit * realm_multiplier)
	attack = int(attack * realm_multiplier)
	defense = int(defense * realm_multiplier)
	
	# 应用装备加成
	for slot in equipment:
		var item = equipment[slot]
		if item:
			max_health += item.health_bonus
			max_spirit += item.spirit_bonus
			attack += item.attack_bonus
			defense += item.defense_bonus
			speed += item.speed_bonus
	
	# 确保当前值不超过最大值
	current_health = min(current_health, max_health)
	current_spirit = min(current_spirit, max_spirit)

# 获得经验值
func gain_experience(amount: int) -> void:
	experience += amount
	emit_signal("experience_gained", amount, experience)
	
	# 检查是否升级
	while experience >= experience_to_next_level:
		experience -= experience_to_next_level
		_level_up()

# 升级
func _level_up() -> void:
	level += 1
	
	# 计算下一级所需经验
	experience_to_next_level = int(experience_to_next_level * 1.5)
	
	# 检查是否突破境界
	var old_realm = cultivation_realm
	_check_realm_breakthrough()
	
	# 更新属性
	_update_stats()
	
	# 恢复满状态
	current_health = max_health
	current_spirit = max_spirit
	
	# 发出信号
	emit_signal("level_up", level, cultivation_realm != old_realm)

# 检查境界突破
func _check_realm_breakthrough() -> bool:
	# 简单的境界突破逻辑，根据等级判断
	var breakthrough = false
	
	if level >= 30 and cultivation_realm < CultivationRealm.ASCENSION:
		cultivation_realm = CultivationRealm.ASCENSION
		breakthrough = true
	elif level >= 25 and cultivation_realm < CultivationRealm.DIVINITY_3:
		cultivation_realm = CultivationRealm.DIVINITY_3
		breakthrough = true
	elif level >= 22 and cultivation_realm < CultivationRealm.DIVINITY_2:
		cultivation_realm = CultivationRealm.DIVINITY_2
		breakthrough = true
	elif level >= 20 and cultivation_realm < CultivationRealm.DIVINITY_1:
		cultivation_realm = CultivationRealm.DIVINITY_1
		breakthrough = true
	elif level >= 18 and cultivation_realm < CultivationRealm.NASCENT_SOUL_3:
		cultivation_realm = CultivationRealm.NASCENT_SOUL_3
		breakthrough = true
	elif level >= 16 and cultivation_realm < CultivationRealm.NASCENT_SOUL_2:
		cultivation_realm = CultivationRealm.NASCENT_SOUL_2
		breakthrough = true
	elif level >= 14 and cultivation_realm < CultivationRealm.NASCENT_SOUL_1:
		cultivation_realm = CultivationRealm.NASCENT_SOUL_1
		breakthrough = true
	elif level >= 12 and cultivation_realm < CultivationRealm.CORE_FORMATION_3:
		cultivation_realm = CultivationRealm.CORE_FORMATION_3
		breakthrough = true
	elif level >= 10 and cultivation_realm < CultivationRealm.CORE_FORMATION_2:
		cultivation_realm = CultivationRealm.CORE_FORMATION_2
		breakthrough = true
	elif level >= 8 and cultivation_realm < CultivationRealm.CORE_FORMATION_1:
		cultivation_realm = CultivationRealm.CORE_FORMATION_1
		breakthrough = true
	elif level >= 6 and cultivation_realm < CultivationRealm.FOUNDATION_3:
		cultivation_realm = CultivationRealm.FOUNDATION_3
		breakthrough = true
	elif level >= 4 and cultivation_realm < CultivationRealm.FOUNDATION_2:
		cultivation_realm = CultivationRealm.FOUNDATION_2
		breakthrough = true
	elif level >= 3 and cultivation_realm < CultivationRealm.FOUNDATION_1:
		cultivation_realm = CultivationRealm.FOUNDATION_1
		breakthrough = true
	elif level >= 2 and cultivation_realm < CultivationRealm.QI_REFINING_3:
		cultivation_realm = CultivationRealm.QI_REFINING_3
		breakthrough = true
	elif level >= 1 and cultivation_realm < CultivationRealm.QI_REFINING_2:
		cultivation_realm = CultivationRealm.QI_REFINING_2
		breakthrough = true
	
	return breakthrough

# 受到伤害
func take_damage(amount: int) -> void:
	current_health -= max(1, amount - defense / 2)
	current_health = max(0, current_health)
	
	emit_signal("health_changed", current_health, max_health)

# 治疗生命值
func heal(amount: int) -> void:
	current_health += amount
	current_health = min(current_health, max_health)
	
	emit_signal("health_changed", current_health, max_health)

# 消耗真气
func consume_spirit(amount: int) -> bool:
	if current_spirit >= amount:
		current_spirit -= amount
		emit_signal("spirit_changed", current_spirit, max_spirit)
		return true
	return false

# 恢复真气
func recover_spirit(amount: int) -> void:
	current_spirit += amount
	current_spirit = min(current_spirit, max_spirit)
	
	emit_signal("spirit_changed", current_spirit, max_spirit)

# 学习技能
func learn_skill(skill) -> bool:
	# 检查是否已学习该技能
	for existing_skill in skills:
		if existing_skill.skill_name == skill.skill_name:
			return false
	
	# 添加技能
	skills.append(skill)
	
	# 如果激活技能数量未满，自动装备
	if active_skills.size() < max_active_skills:
		active_skills.append(skill)
	
	return true

# 装备技能
func equip_skill(skill_index: int) -> bool:
	if skill_index < 0 or skill_index >= skills.size():
		return false
	
	if active_skills.size() >= max_active_skills:
		return false
	
	active_skills.append(skills[skill_index])
	return true

# 卸下技能
func unequip_skill(active_skill_index: int) -> bool:
	if active_skill_index < 0 or active_skill_index >= active_skills.size():
		return false
	
	active_skills.remove_at(active_skill_index)
	return true

# 添加物品到背包
func add_item(item) -> bool:
	# 检查背包是否已满
	if inventory.size() >= max_inventory_size:
		return false
	
	# 检查是否可以堆叠
	for existing_item in inventory:
		if existing_item.item_name == item.item_name and existing_item.stack_size < existing_item.max_stack:
			# 计算可以堆叠的数量
			var space_left = existing_item.max_stack - existing_item.stack_size
			var stack_amount = min(space_left, item.stack_size)
			
			# 增加堆叠数量
			existing_item.stack_size += stack_amount
			item.stack_size -= stack_amount
			
			# 如果物品还有剩余，继续检查其他位置
			if item.stack_size <= 0:
				emit_signal("inventory_changed")
				return true
	
	# 如果物品无法完全堆叠或没有找到可堆叠的位置，添加为新物品
	if inventory.size() < max_inventory_size:
		inventory.append(item)
		emit_signal("inventory_changed")
		return true
	
	return false

# 从背包移除物品
func remove_item(item_index: int) -> bool:
	if item_index < 0 or item_index >= inventory.size():
		return false
	
	var item = inventory[item_index]
	
	# 减少堆叠数量
	item.stack_size -= 1
	
	# 如果堆叠数量为0，移除物品
	if item.stack_size <= 0:
		inventory.remove_at(item_index)
	
	emit_signal("inventory_changed")
	return true

# 使用物品
func use_item(item_index: int) -> bool:
	if item_index < 0 or item_index >= inventory.size():
		return false
	
	var item = inventory[item_index]
	
	# 使用物品
	if item.use(self):
		# 如果堆叠数量为0，移除物品
		if item.stack_size <= 0:
			inventory.remove_at(item_index)
		
		emit_signal("inventory_changed")
		return true
	
	return false

# 装备物品
func equip_item(item_index: int) -> bool:
	if item_index < 0 or item_index >= inventory.size():
		return false
	
	var item = inventory[item_index]
	
	# 检查物品是否可装备
	if not item.can_equip:
		return false
	
	# 获取装备槽位
	var slot = item.equip_slot
	
	# 卸下当前装备
	if equipment.has(slot) and equipment[slot] != null:
		# 将当前装备放回背包
		add_item(equipment[slot])
	
	# 装备新物品
	equipment[slot] = item
	
	# 从背包移除
	inventory.remove_at(item_index)
	
	# 更新属性
	_update_stats()
	
	emit_signal("equipment_changed", slot, item)
	emit_signal("inventory_changed")
	return true

# 卸下装备
func unequip_item(slot: int) -> bool:
	if not equipment.has(slot) or equipment[slot] == null:
		return false
	
	# 检查背包是否有空间
	if inventory.size() >= max_inventory_size:
		return false
	
	# 将装备放回背包
	var item = equipment[slot]
	inventory.append(item)
	
	# 清空装备槽
	equipment[slot] = null
	
	# 更新属性
	_update_stats()
	
	emit_signal("equipment_changed", slot, null)
	emit_signal("inventory_changed")
	return true

# 获取境界名称
func get_realm_name() -> String:
	match cultivation_realm:
		CultivationRealm.QI_REFINING_1:
			return "练气期初期"
		CultivationRealm.QI_REFINING_2:
			return "练气期中期"
		CultivationRealm.QI_REFINING_3:
			return "练气期后期"
		CultivationRealm.FOUNDATION_1:
			return "筑基期初期"
		CultivationRealm.FOUNDATION_2:
			return "筑基期中期"
		CultivationRealm.FOUNDATION_3:
			return "筑基期后期"
		CultivationRealm.CORE_FORMATION_1:
			return "金丹期初期"
		CultivationRealm.CORE_FORMATION_2:
			return "金丹期中期"
		CultivationRealm.CORE_FORMATION_3:
			return "金丹期后期"
		CultivationRealm.NASCENT_SOUL_1:
			return "元婴期初期"
		CultivationRealm.NASCENT_SOUL_2:
			return "元婴期中期"
		CultivationRealm.NASCENT_SOUL_3:
			return "元婴期后期"
		CultivationRealm.DIVINITY_1:
			return "化神期初期"
		CultivationRealm.DIVINITY_2:
			return "化神期中期"
		CultivationRealm.DIVINITY_3:
			return "化神期后期"
		CultivationRealm.ASCENSION:
			return "飞升期"
		_:
			return "未知境界"

# 获取灵根名称
func get_spirit_root_names() -> String:
	if spirit_roots.size() == 0:
		return "无灵根"
	
	var root_names = []
	for root in spirit_roots:
		match root:
			SpiritRoot.FIRE:
				root_names.append("火")
			SpiritRoot.WATER:
				root_names.append("水")
			SpiritRoot.WOOD:
				root_names.append("木")
			SpiritRoot.METAL:
				root_names.append("金")
			SpiritRoot.EARTH:
				root_names.append("土")
			SpiritRoot.WIND:
				root_names.append("风")
			SpiritRoot.THUNDER:
				root_names.append("雷")
			SpiritRoot.ICE:
				root_names.append("冰")
			SpiritRoot.LIGHT:
				root_names.append("光")
			SpiritRoot.DARK:
				root_names.append("暗")
			SpiritRoot.CHAOS:
				root_names.append("混沌")
	
	# 根据灵根数量返回不同描述
	if spirit_roots.size() == 1:
		return root_names[0] + "灵根"
	elif spirit_roots.size() == 2:
		return root_names[0] + root_names[1] + "双灵根"
	elif spirit_roots.size() == 3:
		return root_names[0] + root_names[1] + root_names[2] + "三灵根"
	elif spirit_roots.size() == 4:
		return root_names[0] + root_names[1] + root_names[2] + root_names[3] + "四灵根"
	elif spirit_roots.size() == 5:
		return "五行灵根"
	else:
		return "变异灵根"

# 获取灵根品质名称
func get_spirit_root_quality_name() -> String:
	match spirit_root_quality:
		SpiritRootQuality.WEAK:
			return "劣等"
		SpiritRootQuality.NORMAL:
			return "普通"
		SpiritRootQuality.GOOD:
			return "良好"
		SpiritRootQuality.EXCELLENT:
			return "优秀"
		SpiritRootQuality.SUPERIOR:
			return "上品"
		SpiritRootQuality.SUPREME:
			return "极品"
		_:
			return "未知"

# 设置当前修炼功法
func set_cultivation_technique(technique) -> void:
	cultivation_technique = technique
	
	# 更新玩家属性以应用功法加成
	_update_stats()
	
	# 发出装备变更信号
	emit_signal("equipment_changed", -1, null)
